package com.mingtu.jgspatrol.fragment;

import android.content.Intent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.SendTaskDetailsActivity;
import com.mingtu.jgspatrol.adapter.NavAdapter1;
import com.mingtu.jgspatrol.bean.IndexTaskBean;
import com.mingtu.jgspatrol.databinding.FragmentNav1Binding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class Nav1Fragment extends BaseBindingFragment<FragmentNav1Binding> implements LazyFragmentPagerAdapter.Laziable {
    private NavAdapter1 navAdapter1;
    private List<IndexTaskBean.PageBean.ListBean> DataBean = new ArrayList<>();
    private int currentPage = 1;
    private boolean isLoadMore = true;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_nav1;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext().getApplicationContext());
        binding.recycler.setLayoutManager(linearLayoutManager);

        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_dive_line));
        binding.recycler.addItemDecoration(divider);

        navAdapter1 = new NavAdapter1(context, DataBean);
        binding.recycler.setAdapter(navAdapter1);
        navAdapter1.setOnItemClickListener(new NavAdapter1.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String taskId = DataBean.get(position).getId() + "";
                String sourceType = DataBean.get(position).getType() + "";
                if (sourceType.equals("2")) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("taskId", taskId);
//                    bundle.putString("sourceType", sourceType);
//                    IntentUtils.getInstance().readyGo(getActivity(), SendTaskDetailsActivity.class, bundle);

                    Intent intent = new Intent(getActivity(), SendTaskDetailsActivity.class);
                    intent.putExtra("taskId", taskId);
                    intent.putExtra("sourceType", sourceType);
                    startActivityForResult(intent, 100);

                } else {
                    ToastUtils.showLong("巡护任务没有详情哦~");
                }
            }
        });

    }

    @Override
    protected void getData() {
        getIndexList(1);
//        initListener();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == 200) {
                //完成首页的任务之后刷新数据
                refresh();
            }
        }
    }

//    private void initListener() {
//        initPullRefresh();//刷新
//        initLoadMoreListener();//加载更多
//
//        srlUp.setEnableFooterTranslationContent(false);//是否上拉Footer的时候向上平移列表或者内容
//        srlUp.setEnablePureScrollMode(true);
//    }
//
//    private void initPullRefresh() {
//        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
//        srlUp.setEnableRefresh(false);
//
//    }
//
//    private void initLoadMoreListener() {
//        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                if (isLoadMore) {
//                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
//                    getIndexList(currentPage);
//                }
//                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
//            }
//        });
//
//    }

    /**
     * 首页待完成的任务列表
     */
    public void getIndexList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_TASK)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                IndexTaskBean indexTaskBean = new IndexTaskBean();
                                indexTaskBean = gson.fromJson(result, IndexTaskBean.class);
                                List<IndexTaskBean.PageBean.ListBean> dataBeans = indexTaskBean.getPage().getList();


                                try {
                                    binding.emptyLayout.setIsShowView(false);
                                    binding.recycler.setVisibility(View.VISIBLE);


                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;

                                        ((IndexFragment) (Nav1Fragment.this.getParentFragment())).getIsLoadMoreArray()[0] = isLoadMore;

                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    binding.emptyLayout.setIsShowView(true);
                                                    binding.recycler.setVisibility(View.GONE);
                                                }

                                            }
                                        }
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            navAdapter1.clearData();
                                        }
                                        Collections.reverse(dataBeans);
                                        DataBean.addAll(dataBeans);
                                        navAdapter1.upData(DataBean);
                                        ((IndexFragment) (Nav1Fragment.this.getParentFragment())).setIndexTaskDataBean(DataBean);

                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            binding.recycler.setVisibility(View.GONE);
                                            binding.emptyLayout.setIsShowView(true);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                //显示占位图
                                binding.recycler.setVisibility(View.GONE);
                                binding.emptyLayout.setIsShowView(true);
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });

    }

    /**
     * 刷新数据
     */
    public void refresh() {
        getIndexList(1);
    }


}